/*!
  \file mtf.h
  \brief Implementation to encode and decode strings using the Move-To-Front
  algorithms.
*/


#ifndef _MTF_H_
#define _MTF_H_

int mtfencode(unsigned char *dst, unsigned char *src, int length);
int mtfdecode(unsigned char* dst, unsigned char* src, int length);

/**
  Encodes a string using the move-to-front algorithm.
  \param dst - Array of char where the encoded string will be returned.
  \param src - Array of char representing the string to be encoded.
  \param length - Number of characters in the string to be encoded.
  \return Returns -1 if there's an error in the process; 0 otherwise.
*/
int mtfencode(unsigned char *dst, unsigned char *src, int length)
{
  int i, j;
  unsigned char table[256];

  for (i = 0; i < 256; i++)
    table[i] = i;
  for (i = 0; i < length; i++){
    for (j = 0; j < 256; j++)
      if (src[i] == table[j])
        break;
    if (j >= 256)
      return -1;
    dst[i] = j;
    for( ; j > 0; j--)
      table[j] = table[j-1];
    table[0] = src[i];
  }
  dst[i] = '\0';
  return 0;
}

/**
  Decodes a string encoded using the move-to-front algorithm.
  \param dst - Array of char where the decoded string will be returned.
  \param src - Array of char representing the string to be decoded.
  \param length - Number of characters in the string to be decoded.
*/
int mtfdecode(unsigned char *dst, unsigned char *src, int length)
{
  int i, j;
  char table[256];
  for(i = 0; i < 256; i++)
    table[i] = i;
  for(i = 0; i < length; i++){
    dst[i] = table[src[i]];
    for(j = src[i]; j > 0; j--)
      table[j] = table[j-1];
    table[0] = dst[i];
  }
  dst[i] = '\0';
}

#endif

